<template>
  <div class="app-container">
    <el-card class="box-card" :body-style="{ 'min-height': 'calc(100vh - 110px)',padding: '24px' }">
      <div class="comp-tree">
        <el-input
          v-model="filterText"
          placeholder="输入关键字进行过滤"
          suffix-icon="el-icon-search"
          clearable
          style="width:30%"
        />

        <el-tree
          ref="tree"
          v-loading="loading"
          :data="treeData"
          default-expand-all
          node-key="id"
          :filter-node-method="filterNode"
          :expand-on-click-node="false"
          :props="treeProps"
          style="margin-top: 20px;"
        >
          <!-- <span slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-button
                type="text"
                size="mini"
                icon="el-icon-plus"
                @click="() => append(data)"
              />
              <el-button
                type="text"
                size="mini"
                icon="el-icon-edit"
                @click="() => remove(node, data)"
              />
            </span>
          </span> -->
          <!-- <span slot-scope="{ node, data }" class="custom-tree-node">
            <span>{{ node.label }}</span>
            <el-dropdown
              trigger="click"
              @command="command => handleCommand(command, data, node)"
            >
              <span class="el-dropdown-link">
                <i class="el-icon-more" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="data.permissionType != 'url'" command="insert">新增</el-dropdown-item>
                <el-dropdown-item v-if="!data.noEdit" command="modify">编辑</el-dropdown-item>
                <el-dropdown-item v-if="!data.noEdit && (!data.children || data.children.length ===0)" command="delete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </span> -->
          <div slot-scope="{ node, data }" class="comp-tr-node">
            <template>
              <span class="comp-tr-node--name">
                {{ node.label }}
              </span>
              <!-- 按钮 -->
              <span class="comp-tr-node--btns">
                <!-- 新增 -->
                <el-button
                  v-if="data.permissionType != 'url'"
                  icon="el-icon-plus"
                  size="mini"
                  circle
                  type="primary"
                  @click="handleCreate(data, node)"
                />

                <!-- 编辑 -->
                <el-button
                  v-if="!data.noEdit"
                  icon="el-icon-edit"
                  size="mini"
                  circle
                  type="info"
                  @click="handleUpdate(data, node)"
                />

                <!-- 删除 -->
                <el-button
                  v-if="!data.noEdit && (!data.children || data.children.length ===0)"
                  icon="el-icon-delete"
                  size="mini"
                  circle
                  type="danger"
                  @click="handleDelete(data, node)"
                />
              </span>
            </template>
          </div>
        </el-tree>
      </div>
    </el-card>

    <!-- dialog -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="30%">
      <el-form ref="dataForm" :rules="rules" :model="resource" label-position="left" label-width="90px" style="width: 80%; margin-left:50px;">
        <el-form-item label="资源名称" prop="permissionName">
          <el-input v-model="resource.permissionName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="资源类型" prop="permissionType">
          <el-select v-model="resource.permissionType" clearable :disabled="isPermissionTypeDisabled" placeholder="请选择类型">
            <el-option label="module" value="module" />
            <el-option label="url" value="url" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="resource.permissionType === 'url'" label="权限标识" prop="permissionExpression">
          <el-input v-model="resource.permissionExpression" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item v-if="resource.permissionType === 'url'" label="url地址" prop="permissionUrl">
          <el-input v-model="resource.permissionUrl" placeholder="请输入url地址" />
        </el-form-item>
        <el-form-item v-if="resource.permissionType === 'url'" label="请求类型" prop="httpMethod">
          <el-radio-group v-model="resource.httpMethod">
            <el-radio label="GET" />
            <el-radio label="POST" />
            <el-radio label="PUT" />
            <el-radio label="DELETE" />
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getPermissionTreeData, addPermission, updatePermission, deletePermission } from '@/api/permission.js'

import { convertTreeData } from '@/utils'

import { mapGetters } from 'vuex'

export default {
  name: 'ResourceManagement',
  data() {
    return {
      isPermissionTypeDisabled: false,
      currentData: null,
      treeData: [],
      treeProps: {
        label: 'permissionName',
        children: 'children'
      },
      filterText: '',
      loading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      resource: {
        id: '',
        parentId: '',
        permissionName: '',
        permissionType: '',
        permissionExpression: '',
        permissionUrl: '',
        httpMethod: ''
      },
      rules: {
        permissionName: [{ required: true, message: '权限名称不能为空', trigger: 'change' }],
        permissionType: [{ required: true, message: '权限类型不能为空', trigger: 'change' }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'system'
    ])
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getResourceList()
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    resetResourceProp() {
      this.resource = {
        id: '',
        parentId: '',
        permissionName: '',
        permissionType: '',
        permissionExpression: '',
        permissionUrl: '',
        httpMethod: ''
      }
    },
    handleCommand(command, data, node) {
      const handler = {
        insert: this.handleCreate,
        modify: this.handleUpdate,
        delete: this.handleDelete
      }
      if (handler[command]) {
        handler[command](data, node)
      }
    },
    getResourceList() {
      this.loading = true
      getPermissionTreeData().then(response => {
        const res = response.retBody
        if (res && res.length > 0) {
          const permissionTree = convertTreeData(res)
          permissionTree[0].noEdit = true
          this.treeData.length = 0
          this.treeData = [...permissionTree]
        }
      }).finally(() => {
        setTimeout(() => {
          this.loading = false
        }, 1 * 1000)
      })
    },
    handleCreate(data, node) {
      this.resetResourceProp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.isPermissionTypeDisabled = false
      this.resource.parentId = data.id
      this.currentData = data
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(data, node) {
      this.resource = { ...data }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.isPermissionTypeDisabled = false
      this.currentData = data
      if (this.resource.permissionType === 'module' && this.currentData.children && this.currentData.children.length > 0) {
        this.isPermissionTypeDisabled = true
      }

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(data, node) {
      this.$confirm('确定要删除该条资源信息?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePermission(data.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除资源信息成功',
            type: 'success',
            duration: 1000
          })
          const parent = node.parent
          const children = parent.data.children || parent.data
          const index = children.findIndex(d => d.id === data.id)
          children.splice(index, 1)
        })
      }).catch(() => {

      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addPermission(this.resource).then(response => {
            const res = response.retBody
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '新增资源成功',
              type: 'success',
              duration: 1500
            })
            this.resource.id = res
            if (!this.currentData.children) {
              this.$set(this.currentData, 'children', [])
            }
            this.currentData.children.push(this.resource)
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updatePermission(this.resource.id, this.resource).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改资源信息成功',
              type: 'success',
              duration: 1500
            })

            this.currentData.permissionName = this.resource.permissionName
            this.currentData.permissionType = this.resource.permissionType
            this.currentData.permissionExpression = this.resource.permissionExpression
            this.currentData.permissionUrl = this.resource.permissionUrl
            this.currentData.httpMethod = this.resource.httpMethod
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
 .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 10px;
  }
  /* common */
	.show-btns{
		opacity: 1;
	}
	/* common end */
	.comp-tree{
		width: 100%;
		max-width: 700px;
		max-height: 80vh;
		padding: 2em;
		overflow: auto;
		// 顶部按钮
		.comp-tr-top{
			width: 100px;
			margin-bottom: 2em;
		}
		// 自定义节点
		.comp-tr-node{
			// label
			.comp-tr-node--name{
				display: inline-block;
				line-height: 40px;
				min-height: 40px;
				// 新增
				&.is-new{
					font-weight: bold;
				}
			}
			// button
			.comp-tr-node--btns{
				margin-left: 10px;
				opacity: 0;
				transition: opacity .1s;
				.el-button{
					transform: scale(0.8);// 缩小按钮
					& + .el-button{
						margin-left: -1px;
					}
				}
			}
		}
		// 高亮显示按钮
		.is-current{
			&>.el-tree-node__content{
				.comp-tr-node--btns{
					@extend .show-btns;
				}
			}
		}
		// 悬浮显示按钮
		.el-tree-node__content{
			&:hover{
				.comp-tr-node--btns{
					@extend .show-btns;
				}
			}
		}
	}
</style>
